<?php

class WebUser extends CWebUser {

    public $name;

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;
    public $loginUrl = array('admin/home/login');

    /**
     * Overrides a Yii method that is used for roles in controllers (accessRules).
     *
     * @param string $operation Name of the operation required (here, a role).
     * @param mixed $params (opt) Parameters for this operation, usually the object to access.
     * @return bool Permission granted?
     */
    public function checkAccess($operation, $params = array()) {
        if (empty($this->getUser()->id)) {
            // Not identified => no rights
            return false;
        }
        return true;
        $role = $this->getState("roles");
        if ($role === 'administrator') {
            return true; // admin role has access to everything
        }
        // allow access if the operation request is the current user's role
        return ($operation === $role);
    }

    public function is_login() {
        $session = new CHttpSession;
        $session->open();
        if (isset($session['user']) && $session['user'] != NULL) {
            return TRUE;
        }
        else
            return FALSE;
    }

    /**
     * 
     * @return type
     */
    public function getUser() {
        $session = new CHttpSession;
        $session->open();        
        $user = new User();
        if (isset($session['user']) && $session['user'] != NULL)
            $user = $session['user'];        
        return $user;
    }

    public function updateUser() {
        $userID = $this->getUser()->id;
        $user = User::model()->findByPk($userID);
        if ($user->login())
            return TRUE;
        else
            return FALSE;
    }

    // This is a function that checks the field 'role'
    // in the User model to be equal to 1, that means it's admin
    // access it by Yii::app()->user->isAdmin()
    function isAdmin() {
        $user = $this->loadUser($this->getUser()->id);
        return $user->userRole->name == 'administrator';
    }

    // Load user model.
    protected function loadUser($id = null) {
        if ($this->_model === null) {
            if ($id !== null)
                $this->_model = User::model()->findByPk($id);
        }
        return $this->_model;
    }
    
    function getUserRole(){        
        $user = $this->loadUser(Yii::app()->user->id);
        if ($user == NULL) {
            return FALSE;
        }
        return $user->role;
    }

}

?>
